package jp.co.baka.gae.example.controller.view.bbs;

import java.util.ArrayList;
import java.util.List;

import jp.co.baka.gae.example.meta.BbsMessageMeta;
import jp.co.baka.gae.example.model.BbsMessage;
import jp.co.baka.gae.example.util.LabelValue;
import jp.co.baka.gae.example.util.PerformanceChecker;
import jp.co.baka.gae.lib.MyController;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

public class IndexController extends MyController {


    /**
     * runが呼ばれる前の処理
     *
     */
    @Override
    public  Navigation setUp() {
        return null;
    }

    @Override
    public Navigation run() {



        BbsMessageMeta bbsMeta = new BbsMessageMeta();

        int count = 1;
        try {
            count = Datastore.query(bbsMeta).countQuickly();
        } catch (NullPointerException e) {
            count = Datastore.query(bbsMeta).asKeyList().size();
        }



        final int LIMIT = 100;

        List<LabelValue> pagingOptions = new ArrayList<LabelValue>();
        int pageSize = count/LIMIT + 1;
        for(int i=1;i<=pageSize;i++){
            pagingOptions.add(new LabelValue(String.valueOf(i),String.valueOf(i)));
        }
        requestScope("pagingOptions",pagingOptions);


//      int offsetIndex = asInteger("offsetIndex");
        int offset = 0;
        String offsetIndex = super.param("offsetIndex");
        if(offsetIndex != null){
            offset = (Integer.valueOf(offsetIndex)-1)*LIMIT;
        }

        PerformanceChecker timer = PerformanceChecker.get();
        List<BbsMessage> bbsList = Datastore.query(bbsMeta)
                    .sort(bbsMeta.id.desc)
                    .offset(offset)
                    .limit(LIMIT)
                    .asList();

        requestScope("processTime",timer.getProcessTimeMills());

        requestScope("bbsList",bbsList);

        return forward("./index.jsp");

    }

    /**
     * runが呼ばれた後の処理
     */
    @Override
    public void tearDown() {


    }


    /**
     * runで例外発生時処理
     *
     */
    @Override
    public Navigation handleError(Throwable error) {

        return forward("/bbs/index.jsp");

//        if (error instanceof Error) {
//            throw (Error) error;
//        }
//        if (error instanceof RuntimeException) {
//            throw (RuntimeException) error;
//        }
//        throw new WrapRuntimeException(error);
    }
}